<template>
  <el-row>
    <el-col :span="24">
      <el-menu
        background-color="#334154"
        class="el-menu-vertical-demo"
        default-active="1"
        text-color="#fff"
        active-text-color="#4486ed"
        :collapse="collapsed"
        :show-timeout="100"
        @open="handleOpen"
        @close="handleClose"
        :style="{ width: collapsed ? '64px' : '200px' }"
      >
        <!-- Static Menu Item -->
        <el-menu-item index="0" disabled class="center-text">
          <el-icon>
            <ElementPlus />
          </el-icon>
          <span v-if="!collapsed">考试管理系统</span>
        </el-menu-item>

        <!-- Dynamic Menu Items -->
        <template v-for="menuItem in menuItems" :key="menuItem.index">
          <el-menu-item v-if="!menuItem.items" :index="menuItem.route" class="center-text" @click="() => handleClick(menuItem)">
            <el-icon>
              <component :is="menuItem.icon" />
            </el-icon>
            <span v-if="!collapsed">{{ menuItem.title }}</span>
          </el-menu-item>

          <el-sub-menu v-else :index="menuItem.index">
            <template #title>
              <el-icon>
                <component :is="menuItem.icon" />
              </el-icon>
              <span v-if="!collapsed">{{ menuItem.title }}</span>
            </template>
            <el-menu-item-group>
              <el-menu-item
                v-for="subItem in menuItem.items"
                :key="subItem.index"
                :index="subItem.route"
                class="center-text"
                @click="() => handleClick(subItem)"
              >
                <el-icon>
                  <component :is="subItem.icon" />
                </el-icon>
                <span v-if="!collapsed">{{ subItem.title }}</span>
              </el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </template>
      </el-menu>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted, markRaw } from 'vue';
import { useRouter } from 'vue-router';
import http from '../utils/request';
import { eventBus } from '@/utils/eventBus.js';
import {
  Menu as IconMenu,
  Ticket as IconTicket,
  PieChart as IconPieChart,
  DataLine as IconDataLine,
  Setting as IconSetting,
  Odometer as IconOdometer,
  House as IconHouse,
  Edit as IconEdit,
  Search as IconSearch,
  Calendar as IconCalendar,
  Bell as IconBell,
  User as IconUser
} from '@element-plus/icons-vue';

// Define props
const props = defineProps({
  collapsed: {
    type: Boolean,
    default: false
  }
});

// Create a mapping from icon names to components
const iconMap: Record<string, any> = {
  'el-icon-menu': markRaw(IconMenu),
  'el-icon-bangzhu': markRaw(IconTicket),
  'el-icon-pie-chart': markRaw(IconPieChart),
  'el-icon-data-line': markRaw(IconDataLine),
  'el-icon-setting': markRaw(IconSetting),
  'el-icon-odometer': markRaw(IconOdometer),
  'el-icon-house': markRaw(IconHouse),
  'el-icon-edit': markRaw(IconEdit),
  'el-icon-search': markRaw(IconSearch),
  'el-icon-calendar': markRaw(IconCalendar),
  'el-icon-bell': markRaw(IconBell),
  'el-icon-user': markRaw(IconUser)
  // Add more icon mappings as needed
};

const router = useRouter();
const menuItems = ref<any[]>([]);
const existingTabs = new Set();

// Function to get icon component by name
const getIcon = (iconName: string) => {
  return iconMap[iconName] || iconMap['el-icon-menu']; // Default to IconMenu if iconName is not found
};

// Handle menu item click
const handleClick = (menuItem: any) => {
  addTab(menuItem.title, menuItem.route);
};

// Function to add a new tab or switch to an existing tab
const addTab = (title: string, routeName: string) => {
  if (existingTabs.has(title)) {
    eventBus.value.emit('switch-tab', title);
    router.push(`/home/${routeName}`);
    return;
  }
  existingTabs.add(title);
  eventBus.value.emit('add-tab', {
    title: title,
    name: routeName,
    component: routeName
  });
  router.push(`/home/${routeName}`);
};

// Process menu data
const processMenuData = (data: any[]) => {
  menuItems.value = data.map((item, index) => {
    const menuItem: any = {
      index: String(index),
      title: item.topMenuName,
      route: item.url ? item.url.replace(/^\//, '') : '',
      icon: getIcon(item.topIcon),
    };

    if (item.submenu) {
      menuItem.items = item.submenu.map((subItem, subIndex) => ({
        index: `${index}-${subIndex}`,
        title: subItem.name,
        route: subItem.url ? subItem.url.replace(/^\//, '') : '',
        icon: getIcon(subItem.icon), // Ensure sub-menu icons are correctly mapped
      }));
    }

    return menuItem;
  });
};

// Fetch menu data
const fetchMenuData = async () => {
  try {
    const response = await http.request({
      url: '/common/getMenu',
      method: 'get'
    });

    if (response && response.data.data) {
      const menuData = JSON.parse(response.data.data);
      console.log(menuData);

      if (Array.isArray(menuData)) {
        processMenuData(menuData);
      } else {
        console.error('menuData is not an array');
      }
    } else {
      console.error('No data found in response');
    }
  } catch (error) {
    console.error('Failed to fetch menu data', error);
  }
};

// Initialize
onMounted(() => {
  fetchMenuData();
});

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
</script>

<style scoped lang="less">
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
}

.el-menu {
  background-color: #334154;
  min-height: 400px;
  height: 100vh;
  border-right: none;
  font-weight: 200;
  font-family: "华文仿宋";
}

.center-text {
  text-align: center;
}
</style>
